package rules

import (
	"api/lib"
	"api/conf"
	"encoding/pem"
	"crypto/x509"
	"crypto/rsa"
	"crypto/rand"
	"encoding/base64"
	"crypto/sha1"
	"crypto"
	"github.com/funlake/gopkg/utils/log"
	"context"
)
var publicKey = []byte(`
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPIA8kIDEPHLp5Wmd+sW2DbATU
C5OuJoqw4ohbvAz/3nUX3+o2irgBAuRD0VTDaoPVfNBQBlVcngRZ4TBgFAWT8zRg
FSz63/48bWWtdMHnnCgueYZInbtkbZEqX1l2cH8KeGM7mLX3H2EJrbHFDW6uBa+k
OMUvLCtzBpnepMFIuwIDAQAB
-----END PUBLIC KEY-----`)
var privateKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDPIA8kIDEPHLp5Wmd+sW2DbATUC5OuJoqw4ohbvAz/3nUX3+o2
irgBAuRD0VTDaoPVfNBQBlVcngRZ4TBgFAWT8zRgFSz63/48bWWtdMHnnCgueYZI
nbtkbZEqX1l2cH8KeGM7mLX3H2EJrbHFDW6uBa+kOMUvLCtzBpnepMFIuwIDAQAB
AoGBAK60nPDc0mSr18IqdieQIw56W2w8Q5neWpeuzFOMP+7Gxj+YGCdfRKtdtApc
FEIsovy9JbyKSxAvHP5vCm3QFY7apT0Nscnip/kdr33cnhAybk6JiQL2vQVN3wIv
ycVb8ayrdF5iL/2EEJpmHnp5+SqaV0ijvuAFrHjoeVjLJw5RAkEA/PL2eBe5X4oa
CzYq46xINKRsPb/WemQxFaAZvfLmeW2l3gZbpC9DYvE1dvsl8xS3SSrsOwTtt7YS
mYMGrZkcGQJBANGfmt17slvFkCxqjtyW6czIwvYYA9F5EmdBTpS9UeC90XIvABeU
3q8ot4x9hJHNRQ3u0PUDsuPY0QtZhAG8JfMCQQD5rRTti3VVwapdYLVLD7YiCB4z
gVVCb/0nPGXMYaNvPnTXx+zTDjf0xOSiMdrOqqcUGMMeqom+qYCIeJWx6wyZAkEA
qocOctMn+2Qyrw9YfLcAJ6nCgHR01rmJcRo9lN6Wdx+z/RGjH4vpw9B50P5jFEFK
xdTbhBaoNpaxKGx/6PFoZQJARVBsf/Tjb5MpYHJRLXHERX3xQN1QABmb7+sVDc4c
VrIhPaUSkBFJQ8gu1RAMsVktZQnQxF2+qiX9LUuviH5AxA==
-----END RSA PRIVATE KEY-----`)
func Sign(proxy types.ProxyContext,ctx context.Context) (bool,int,string){
	//encode,_ := rsaPubEncrypt([]byte(proxy.QueryString))
	sign := proxy.GetSign()
	//dst := base64.StdEncoding.EncodeToString(encode)
	//utils.LogInfo(dst)
	//decode,_ := rsaPriDecrypt(encode)
	//utils.LogSuccess(string(decode))
	//sign := makeSign(proxy.QueryString)
	log.Success(sign)
	if !verifySign(sign,proxy.QueryString + string(proxy.PostData)){
		log.Error("Sign verified fail")
		return false,conf.REQUEST_MERGE_SIGN_ERROR,"验签失败"
	}
	return true,0,"验签成功"
}

//私钥签名
func makeSign(data string) string{
	// Parse private key into rsa.PrivateKey
	PEMBlock, _ := pem.Decode([]byte(privateKey))
	if PEMBlock == nil {
		log.Error("Could not parse private key")
	}
	if PEMBlock.Type != "RSA PRIVATE KEY" {
		log.Error("Found wrong private key type")
	}
	privkey, err := x509.ParsePKCS1PrivateKey(PEMBlock.Bytes)
	if err != nil {
		log.Error(err.Error())
	}
	// Compute the sha1
	h := sha1.New()
	h.Write([]byte(data))
	// Sign the data
	signature, err := rsa.SignPKCS1v15(rand.Reader, privkey, crypto.SHA1, h.Sum(nil))
	if err != nil {
		log.Error(err.Error())
	}
	return base64.StdEncoding.EncodeToString(signature)
}
//公钥验签
func verifySign(sign string,data string) bool{
	// Parse public key into rsa.PublicKey
	PEMBlock, _ := pem.Decode([]byte(publicKey))
	if PEMBlock == nil {
		log.Error("Could not parse public key")
		return false
	}
	if PEMBlock.Type != "PUBLIC KEY" {
		log.Error("Found wrong public key type")
		return false
	}
	pubkey, err := x509.ParsePKIXPublicKey(PEMBlock.Bytes)
	if err != nil {
		log.Error(err.Error())
		return false
	}
	h := sha1.New()
	h.Write([]byte(data))
	signature, err := base64.StdEncoding.DecodeString(sign)
	if err != nil {
		log.Error(err.Error())
		return false
	}
	// Verify
	err = rsa.VerifyPKCS1v15(pubkey.(*rsa.PublicKey), crypto.SHA1, h.Sum(nil), signature)
	if err == nil {
		return true
	}
	return false
}
//// 公钥加密
//func rsaPubEncrypt(origData []byte) ([]byte, error) {
//
//	block, _ := pem.Decode(publicKey)
//	if block == nil {
//		return nil, errors.New("public key error")
//	}
//	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
//	if err != nil {
//		return nil, err
//	}
//	pub := pubInterface.(*rsa.PublicKey)
//	return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
//}
//
//// 私钥解密
//func rsaPriDecrypt(ciphertext []byte) ([]byte, error) {
//	block, _ := pem.Decode(privateKey)
//	if block == nil {
//		return nil, errors.New("private key error!")
//	}
//	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
//	if err != nil {
//		return nil, err
//	}
//	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
//}